<template>
  <div>
    <div 
      v-if="tableObj.topBtnList" 
      :style="{
        marginBottom:'10px',
        display:'flex',
        justifyContent:tableObj.topBtnAlign=='right'?'flex-end':'flex-start'
      }"
    >
      <el-button 
        v-for="item in tableObj.topBtnList" 
        :key='item.key'
        :type="item.type"
        :icon="'el-icon-'+item.icon"
        :size="item.size"
        @click="topBtnClick($event,item.key)"
      >{{item.title}}</el-button>
    </div>
    <vxe-table
        :ref="`table_${tableObj.id}`"
        :key="tableKey"
        border
        resizable
        keep-source
        show-overflow
        highlight-hover-row
        column-key
        :class='tableObj.classname'
        :row-id="tableObj.rowId"
        :height="tableObj.height"
        :stripe="tableObj.stripe ? tableObj.stripe : false"
        :data="tableObj.tableData"
        :loading="tableObj.loading"
        :edit-config="tableObj.editConfig"
        :edit-rules="tableObj.editRules"
        :tree-config="tableObj.treeConfig"
        :checkbox-config="tableObj.checkConfig"
        :radio-config="tableObj.radioConfig"
        :row-class-name="rowClassName"
        :header-cell-class-name="headerCellClassName"
        :cell-class-name="cellClassName"
        :scroll-x="tableObj.scrollX"
        :scroll-y="tableObj.scrollY"
        :show-footer='tableObj.showFooter?tableObj.showFooter:false'
        :footer-method="tableObj.footerMethod"
        @cell-click="cellClickEvent"
        @cell-dblclick="cellDBLClickEvent"
        @header-cell-click="headerCellClickEvent"
        @header-cell-dblclick="headerCellDblclickEvent"
        @cell-mouseenter="cellMouseenterEvent"
        @cell-mouseleave="cellMouseleaveEvent"
        @header-cell-menu="headerCellContextMenuEvent"
        @cell-menu="cellContextMenuEvent"
        @scroll="scrollEvent"
    >
      <template v-for="itemCol in tableObj.columnType">
        <!-- 一级表头 -->
        <template v-if="itemCol.type == 'column'">
          <vxe-table-column
            v-for="item in itemCol.column"
            :key="item.key"
            :field="item.key"
            :title="item.title"
            :sortable="item.sortable ? item.sortable : false"
            :type="item.type"
            :width="item.width ? item.width : 'auto'"
            :min-width="item.minWidth ? item.minWidth : '100'"
            :align="item.align ? item.align : 'center'"
            :fixed="item.fixed ? item.fixed : null"
            :formatter="item.formatter"
            :edit-render="item.editRender"
            :tree-node='item.treeNode'
            :filters="item.filters"
            :filter-method="item.filteMethod"
            :cell-render="item.cellRender"
            :sort-by="item.sortBy"
          >
            <template #default="{ row }" v-if="item.operate">
                <template v-for="itemBtn in item.child">
                    <!-- 按钮型 -->
                    <el-button 
                        v-if="itemBtn.btnType=='button'"
                        :key='itemBtn.key'
                        :type='itemBtn.type'
                        :size="itemBtn.size"
                        :plain='itemBtn.plain'
                        :round="itemBtn.round"
                        :circle="item.circle"
                        :loading="itemBtn.loading?itemBtn.loading:false"
                        :disabled="itemBtn.disabled?itemBtn.disabled:false"
                        :icon="'el-icon-'+itemBtn.icon"
                        @click="operateEvent($event,row,itemBtn.key)"
                    >{{itemBtn.text}}</el-button>

                    <!-- 图标型 -->
                    <i
                        v-if="itemBtn.btnType=='icon'"
                        :key='itemBtn.key'
                        type="text" 
                        :class="'el-icon-'+itemBtn.icon"
                        :style="{
                            color:itemBtn.color,
                            fontSize:itemBtn.size,
                            cursor:'pointer',
                            marginLeft:itemBtn.marginLeft?itemBtn.marginLeft+'px':'10px',
                            marginRight:itemBtn.marginRight?itemBtn.marginRight+'px':'10px',
                        }"
                        @click="operateEvent($event,row,itemBtn.key)"
                    >
                    </i>

                    <!-- 开关 -->
                    <el-switch
                        v-if="itemBtn.btnType=='switch'"
                        :key='itemBtn.key'
                        v-model="row[itemBtn.key]"
                        :active-text="itemBtn.activeText"
                        :inactive-text="itemBtn.inactiveText"
                        :active-color="itemBtn.activeColor"
                        :inactive-color="itemBtn.inactiveColor"
                        :disabled='itemBtn.disabled'
                        @change="operateEvent($event,row,itemBtn.key)"
                    ></el-switch>

                    <!-- 图标按钮组用于单元格行编辑事件 -->
                    <div :key='itemBtn.key' v-if="itemBtn.btnType=='editGroup'" style="display:inline-block;">
                        <template  v-if="$refs[`table_${tableObj.id}`].isActiveByRow(row)" >
                            <i 
                                class="el-icon-check" 
                                :style="{
                                  color:'#67C23A',
                                  fontSize:itemBtn.size?itemBtn.size+'px':'16px',
                                  marginLeft:itemBtn.marginLeft?itemBtn.marginLeft:'8px',
                                  marginRight:itemBtn.marginRight?itemBtn.marginRight:'8px'
                                }" 
                                @click="operateEvent($event,row,'save')"
                            ></i>
                            <i
                                class="el-icon-close" 
                                :style="{
                                  color:'#F56C6C',
                                  fontSize:itemBtn.size?itemBtn.size+'px':'16px',
                                  marginLeft:itemBtn.marginLeft?itemBtn.marginLeft:'8px',
                                  marginRight:itemBtn.marginRight?itemBtn.marginRight:'8px'
                                }" 
                                @click="operateEvent($event,row,'cancel')"
                            ></i>
                        </template>
                        <template v-else>
                            <i
                                class="el-icon-edit" 
                                :style="{
                                  color:'#409EFF',
                                  fontSize:itemBtn.size?itemBtn.size+'px':'16px',
                                  marginLeft:itemBtn.marginLeft?itemBtn.marginLeft:'8px',
                                  marginRight:itemBtn.marginRight?itemBtn.marginRight:'8px'
                                }" 
                                @click="operateEvent($event,row,'edit')"
                            ></i>
                        </template>
                    </div>

                    <!-- 带确认按钮型 -->
                    <el-popconfirm
                      v-if="itemBtn.btnType=='popBtn'"
                      :key='itemBtn.key'
                      :title="itemBtn.content?itemBtn.content:'是否确认删除？'"
                      :placement="itemBtn.placement?itemBtn.placement:'top'"
                      width='150'
                      @confirm="operateEvent($event,row,itemBtn.key)"
                    >
                      <el-button 
                        v-if="itemBtn.popType=='button'" 
                        slot="reference" 
                        :type="itemBtn.type" 
                        size="mini"
                      >{{item.title}}</el-button>
                      <i 
                        v-else 
                        slot="reference" 
                        :class="'el-icon-'+itemBtn.icon" 
                        :style="{
                          color:itemBtn.color?itemBtn.color:'red',
                          fontSize:itemBtn.size,
                          cursor:'pointer',
                          marginLeft:itemBtn.marginLeft?itemBtn.marginLeft+'px':'10px',
                          marginRight:itemBtn.marginRight?itemBtn.marginRight+'px':'10px',
                        }"
                      ></i>
                    </el-popconfirm>
                </template>
            </template>
          </vxe-table-column>
        </template>

        <!-- 二级表头 -->
        <vxe-table-colgroup
          v-if="itemCol.type == 'groupColumn'"
          :title="itemCol.title"
          :key="itemCol.type"
          :align="itemCol.align ? itemCol.align : 'center'"
          :fixed="itemCol.fixed"
        >
          <vxe-table-column
            v-for="item in itemCol.column"
            :key="item.key"
            :field="item.key"
            :title="item.title"
            :width="item.width ? item.width : 'auto'"
            :min-width="item.minWidth ? item.minWidth : '100'"
            :formatter="item.formatter"
            :align="item.align ? item.align : 'center'"
            :edit-render="item.editRender"
            :tree-node='item.treeNode'
            :filters="item.filters"
            :filter-method="item.filteMethod"
            :cell-render="item.cellRender"
            :sort-by="item.sortBy"
          >
          </vxe-table-column>
        </vxe-table-colgroup>
      </template>
    </vxe-table>
  </div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
  props: {
    tableObj: {
      type: Object,
      default: ()=>{return {}},
    },
  },
  watch:{
    tableObj:{
      handler(val, newval) {
      },
      deep: true
    }
  },
  data(){
    return {
      tableKey:0,//强制刷新table用
    }
  },
  created(){
    this.columnDrop1();
  },

  methods: {
    //单元格单击事件
    cellClickEvent(val) {
    this.$emit("cellClickEvent", val);
    },
    //单元格双击事件
    cellDBLClickEvent(val){
        this.$emit('cellDBLClickEvent',val)
    },
    //表头单元格单击事件
    headerCellClickEvent(val){
        this.$emit('headerCellClickEvent',val)
    },
    //表头单元格双击击事件
    headerCellDblclickEvent(val){
        this.$emit('headerCellDblclickEvent',val)
    },
    //鼠标移入单元格
    cellMouseenterEvent(val){
        this.$emit('cellMouseenterEvent',val)
    },
    //鼠标移出单元格
    cellMouseleaveEvent(val){
        this.$emit('cellMouseleaveEvent',val)
    },
    //右键列
    headerCellContextMenuEvent(val){
        this.$emit('headerCellContextMenuEvent',val)
    },
    //右键行
    cellContextMenuEvent(val){
        this.$emit('cellContextMenuEvent',val)
    },
    //表格滚动事件
    scrollEvent(val){
        this.$emit("scrollEvent",val)
    },
    //表格操作事件
    operateEvent(e,row, key) {
      this.$emit("operateEvent", e,row, key);
    },
    //表格上方按钮事件
    topBtnClick(e,key){
      this.$emit("topBtnClick",e,key)
    },
    //行样式修改
    rowClassName({row, rowIndex, column, columnIndex}){
      if(this.tableObj.classname=='testClass'){
        if(rowIndex=='2'){
          return 'row-pink'
        }
      }
    },
    //表头样式更改
    headerCellClassName({row, rowIndex, column, columnIndex}){
      if(this.tableObj.classname=='testClass'){
        if(column.property=='name'){
          return 'header-blue'
        }
      }
    },
    //单元格渲染
    cellClassName({row, rowIndex, column, columnIndex}){
       if(this.tableObj.classname=='testClass'){
        if(column.property=='name'){
          return 'cell-yellow'
        }
      }
    },
    //设置表头属性 key:表头key值  attrName:修改的属性名  attrValue:修改的属性值 isGroup:是否为二级表头
    setHeaderAttribute(key,attrName,attrValue,isGroup=false){
      if(isGroup){
        let i = this.tableObj.col.findIndex((e,index)=>{return e.key == keyName;})
        if(i!=-1){
          this.tableObj.col[i][attrName] = value;
        }
      }else{
        for(let item of this.tableObj.col){
          if(item.type=='column'){
            let i=item.column.findIndex(t=>{return t.key==key});
            if(i!=-1){
              item.column[i][attrName] = attrValue;
              this.tableKey = Math.random();
            }
          }
        }
      }
    },
    //强制刷新table
    reFreshTable(){
      this.tableKey = Math.random();
    },
    //列拖动  不支持多级表头拖动
    columnDrop1(){
      if(this.tableObj.notDrag) return
      this.$nextTick(() => {
          const $table = this.$refs[`table_${this.tableObj.id}`];
          this.sortable2 = Sortable.create($table.$el.querySelector('.body--wrapper>.vxe-table--header .vxe-header--row'), {
            handle: '.vxe-header--column:not(.col--fixed)',
            onEnd: ({ item, newIndex, oldIndex }) => {
              const { fullColumn, tableColumn } = $table.getTableColumn()
              const targetThElem = item
              const wrapperElem = targetThElem.parentNode
              const newColumn = fullColumn[newIndex]
              if (newColumn.fixed) {
                // 错误的移动
                if (newIndex > oldIndex) {
                  wrapperElem.insertBefore(targetThElem, wrapperElem.children[oldIndex])
                } else {
                  wrapperElem.insertBefore(wrapperElem.children[oldIndex], targetThElem)
                }
                return this.$XModal.message({ content: '固定列不允许拖动！', status: 'error' })
              }
              // 转换真实索引
              const oldColumnIndex = $table.getColumnIndex(tableColumn[oldIndex])
              const newColumnIndex = $table.getColumnIndex(tableColumn[newIndex])
              // 移动到目标列
              const currRow = fullColumn.splice(oldColumnIndex, 1)[0]
              fullColumn.splice(newColumnIndex, 0, currRow)
              $table.loadColumn(fullColumn)
            }
          })
        })
      }
    },
    //行合并
    //列合并
}
</script>
